<template>
  <div class="product-trace-result">
    <!-- 产品基本信息 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover" class="product-card">
          <div slot="header" class="card-header">
            <span>产品基本信息</span>
            <el-button type="primary" size="small" @click="exportData">
              <i class="el-icon-download"></i> 导出记录
            </el-button>
          </div>
          <el-descriptions :column="4" border>
            <el-descriptions-item label="产品名称">{{ traceData.product?.name || '--' }}</el-descriptions-item>
            <el-descriptions-item label="产品编号">{{ traceData.product?.code || '--' }}</el-descriptions-item>
            <el-descriptions-item label="产品类别">{{ traceData.product?.category_name || '--' }}</el-descriptions-item>
            <el-descriptions-item label="规格型号">{{ traceData.product?.specification || '--' }}</el-descriptions-item>
            <el-descriptions-item label="等级">{{ traceData.product?.grade || '--' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(traceData.product?.create_time) || '--' }}</el-descriptions-item>
            <el-descriptions-item label="生产状态" :span="2">
              <el-tag :type="getStatusType(traceData.product?.status === 1 ? 'active' : 'discontinued')">
                {{ getStatusText(traceData.product?.status === 1 ? 'active' : 'discontinued') }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>

    <!-- 批次信息 -->
    <el-row :gutter="20" class="materials-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>批次信息</span>
          </div>
          <el-table :data="traceData.batches || []" stripe style="width: 100%">
            <el-table-column prop="batchNo" label="批次号"></el-table-column>
            <el-table-column prop="productionDate" label="生产日期"></el-table-column>
            <el-table-column prop="quantity" label="数量"></el-table-column>
            <el-table-column label="状态">
              <template v-slot="scope">
                <el-tag v-if="scope && scope.row" :type="getBatchStatusType(scope.row.status)">
                  {{ getBatchStatusText(scope.row.status) }}
                </el-tag>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="120">
              <template v-slot="scope">
                <el-button
                  v-if="scope && scope.row"
                  @click.native.prevent="viewBatchDetails(scope.row)"
                  link
                  size="small">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!traceData.batches || traceData.batches.length === 0" class="empty-data">
            <el-empty description="暂无批次数据"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 生产过程追溯 -->
    <el-row :gutter="20" class="process-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>生产过程追溯</span>
          </div>
          <el-collapse v-model="activeProcesses">
            <el-collapse-item 
              v-for="(process, index) in traceData.processes" 
              :key="index"
              :title="process.processName"
              :name="index"
            >
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-descriptions :column="3" border>
                    <el-descriptions-item label="工序编号">{{ process.processId || '--' }}</el-descriptions-item>
                    <el-descriptions-item label="开始时间">{{ process.createTime || '--' }}</el-descriptions-item>
                    <el-descriptions-item label="批次号">{{ process.batchNo || '--' }}</el-descriptions-item>
                    <el-descriptions-item label="操作员">{{ process.operator || '--' }}</el-descriptions-item>
                    <el-descriptions-item label="设备">{{ process.equipment || '--' }}</el-descriptions-item>
                    <el-descriptions-item label="结果">
                      <el-tag :type="getProcessResultType(process?.result)">
                        {{ process?.result || '未知' }}
                      </el-tag>
                    </el-descriptions-item>
                  </el-descriptions>
                </el-col>
              </el-row>
            </el-collapse-item>
          </el-collapse>
          <div v-if="!traceData.processes || traceData.processes.length === 0" class="empty-data">
            <el-empty description="暂无生产过程数据"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 检验记录 -->
    <el-row :gutter="20" class="inspection-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>检验记录</span>
          </div>
          <el-table :data="traceData.inspections || []" stripe style="width: 100%">
            <el-table-column prop="batchNo" label="批次号"></el-table-column>
            <el-table-column prop="paramName" label="检验项目"></el-table-column>
            <el-table-column prop="standardValue" label="标准值"></el-table-column>
            <el-table-column prop="inspector" label="检验员"></el-table-column>
            <el-table-column prop="inspectionTime" label="检验时间"></el-table-column>
            <el-table-column label="检验结果">
              <template v-slot="scope">
                <el-tag v-if="scope && scope.row" :type="scope.row.isQualified === 1 ? 'success' : 'danger'">
                  {{ scope.row.isQualified === 1 ? '合格' : '不合格' }}
                </el-tag>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
              <template v-slot="scope">
                <template v-if="scope && scope.row">
                  <el-button
                    @click.native.prevent="viewInspectionDetails(scope.row)"
                    link
                    size="small">
                    查看详情
                  </el-button>
                  <el-button
                    v-if="scope.row.attachmentUrl"
                    @click.native.prevent="viewCertificate(scope.row.attachmentUrl)"
                    link
                    size="small">
                    查看附件
                  </el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!traceData.inspections || traceData.inspections.length === 0" class="empty-data">
            <el-empty description="暂无检验记录"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 生命周期 -->
    <el-row :gutter="20" class="lifecycle-row" v-if="traceData.lifecycle && traceData.lifecycle.length > 0">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>生产生命周期</span>
          </div>
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in traceData.lifecycle"
              :key="index"
              :type="getTimelineItemType(activity.type)"
              :color="getTimelineItemColor(activity.type)"
              :timestamp="activity.timestamp || ''"
            >
              <h4>{{ activity.title }}</h4>
              <p>{{ activity.description }}</p>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详情对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%">
      <div v-loading="dialogLoading">
        <component :is="currentDetailComponent" :data="detailData"></component>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { exportProductTrace } from "@/api/qep/dataAnalysis";

export default {
  name: "ProductTraceResult",
  props: {
    traceData: {
      type: Object,
      required: true
    },
    productName: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      activeProcesses: [], // 默认展开第一个工序
      dialogVisible: false,
      dialogTitle: '',
      dialogLoading: false,
      currentDetailComponent: null,
      detailData: null
    }
  },
  mounted() {
    // 初始化时默认展开第一个工序
    if (this.traceData && this.traceData.processes && this.traceData.processes.length > 0) {
      this.activeProcesses = [0];
    }
  },
  methods: {
    // 格式化日期时间
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return '--';
      // 如果是ISO格式的日期时间字符串，转换为更友好的格式
      if (dateTimeStr.includes('T')) {
        const date = new Date(dateTimeStr);
        return date.toLocaleString();
      }
      return dateTimeStr;
    },
    
    // 状态类型和文本转换
    getStatusType(status) {
      const statusMap = {
        'active': 'success',
        'discontinued': 'info',
        'pending': 'warning',
        'error': 'danger'
      };
      return statusMap[status] || 'info';
    },
    getStatusText(status) {
      const statusMap = {
        'active': '生产中',
        'discontinued': '已停产',
        'pending': '待生产',
        'error': '异常'
      };
      return statusMap[status] || '未知';
    },
    
    // 批次状态
    getBatchStatusType(status) {
      const statusMap = {
        1: 'success',
        0: 'danger',
        'planning': 'info',
        'in_production': 'warning',
        'completed': 'success',
        'on_hold': 'danger',
        'canceled': 'info'
      };
      return statusMap[status] || 'info';
    },
    getBatchStatusText(status) {
      const statusMap = {
        1: '正常',
        0: '异常',
        'planning': '计划中',
        'in_production': '生产中',
        'completed': '已完成',
        'on_hold': '挂起',
        'canceled': '已取消'
      };
      return statusMap[status] || '未知';
    },
    
    // 工序结果
    getProcessResultType(result) {
      const resultMap = {
        'pass': 'success',
        'fail': 'danger',
        'rework': 'warning'
      };
      return resultMap[result] || 'info';
    },
    getProcessResultText(result) {
      const resultMap = {
        'pass': '通过',
        'fail': '不通过',
        'rework': '返工'
      };
      return resultMap[result] || '未知';
    },
    
    // 时间线项目类型
    getTimelineItemType(type) {
      const typeMap = {
        'design': 'primary',
        'material': 'success',
        'process': 'warning',
        'inspection': 'info',
        'defect': 'danger',
        'delivery': 'success',
        'feedback': 'warning'
      };
      return typeMap[type] || 'primary';
    },
    getTimelineItemColor(type) {
      const colorMap = {
        'design': '#409EFF',
        'material': '#67C23A',
        'process': '#E6A23C',
        'inspection': '#909399',
        'defect': '#F56C6C',
        'delivery': '#67C23A',
        'feedback': '#E6A23C'
      };
      return colorMap[type] || '#409EFF';
    },
    
    // 查看详情
    viewBatchDetails(batch) {
      this.dialogTitle = '批次详情';
      this.detailData = batch;
      this.currentDetailComponent = 'batch-detail';
      this.dialogVisible = true;
    },
    viewInspectionDetails(inspection) {
      this.dialogTitle = '检验详情';
      this.detailData = inspection;
      this.currentDetailComponent = 'inspection-detail';
      this.dialogVisible = true;
    },
    viewCertificate(certificate) {
      this.dialogTitle = '合格证';
      this.detailData = certificate;
      this.currentDetailComponent = 'certificate-detail';
      this.dialogVisible = true;
    },
    
    // 导出数据
    exportData() {
      // 尝试从多个位置获取产品名称
      let productName = this.traceData?.product?.name;
      
      // 如果产品名称不存在，尝试从props获取
      if (!productName && this.productName) {
        productName = this.productName;
      }
      
      if (!productName) {
        this.$message.warning('无法获取产品名称，导出失败');
        return;
      }
      
      this.$message({
        message: '正在导出数据，请稍候...',
        type: 'info'
      });
      
      exportProductTrace(productName).then(() => {
        this.$message.success('导出成功');
      }).catch(err => {
        console.error('导出失败:', err);
        this.$message.error('导出功能暂未实现，请联系管理员添加导出接口');
      });
    },
    
    // 处理产品追溯数据
    processProductTraceData(data) {
      // 确保关键数据结构存在
      if (!data.product) {
        data.product = {
          name: this.productName,
          code: '--',
          category_name: '--',
          specification: '--',
          grade: '--',
          create_time: '--',
          status: 1
        };
      } else {
        // 映射后端返回的字段到前端需要的字段
        data.product = {
          name: data.product.name || this.productName,
          code: data.product.code || '--',
          category_name: data.product.category_name || '--',
          specification: data.product.specification || '--',
          grade: data.product.grade || '--',
          create_time: data.product.create_time || '--',
          status: data.product.status === 1 ? 1 : 0
        };
      }
      
      // 处理批次数据
      if (!data.batches) {
        data.batches = [];
      } else {
        // 如果有需要，可以在这里进行数据转换
      }
      
      // 处理生产过程数据
      if (!data.processes) {
        data.processes = [];
      } else {
        // 对工序进行分组，相同工序名称的合并为一个，并将其子过程放在parameters数组中
        const processMap = new Map();
        
        data.processes.forEach(process => {
          const processName = process.processName;
          
          if (!processMap.has(processName)) {
            processMap.set(processName, {
              processName: processName,
              processId: process.processId || '',
              createTime: process.createTime || '',
              batchNo: process.batchNo || '',
              operator: process.operator || '',
              equipment: process.equipment || '',
              result: process.result || '',
              parameters: [],
              defects: []
            });
          }
          
          // 如果有结果，可能是子过程或参数记录
          if (process.result) {
            processMap.get(processName).parameters.push({
              paramName: process.operationName || '操作',
              value: process.result,
              standardValue: '',
              measureTime: process.createTime || '',
              status: process.result === '合格' ? 'normal' : process.result === '不合格' ? 'error' : 'warning'
            });
          }
        });
        
        // 将Map转换为数组
        data.processes = Array.from(processMap.values());
      }
      
      // 处理检验记录
      if (!data.inspections) {
        data.inspections = [];
      } else {
        // 映射检验记录字段
        data.inspections = data.inspections.map(inspection => ({
          batchNo: inspection.batchNo || `BATCH-${Math.floor(Math.random() * 10000)}`,
          paramName: inspection.paramName || '',
          standardValue: inspection.standardValue || '',
          inspector: inspection.inspector || '',
          inspectionTime: inspection.inspectionTime || '',
          isQualified: inspection.isQualified === 1 ? 1 : 0,
          attachmentUrl: inspection.attachmentUrl || null
        }));
      }
      
      // 处理缺陷数据
      if (!data.defects) {
        data.defects = [];
      } else {
        // 如果有需要，可以在这里进行数据转换
      }
      
      // 处理统计数据
      if (!data.stats) {
        data.stats = {
          qualificationRate: 0,
          inspectedQuantity: 0,
          qualifiedQuantity: 0,
          firstPassRate: 0,
          firstPassQuantity: 0,
          defectCount: 0,
          defectDensity: 0
        };
      }
      
      return data;
    }
  }
}
</script>

<style scoped>
.product-trace-result {
  margin-top: 20px;
}
.product-card {
  margin-bottom: 20px;
}
.timeline-row, .materials-row, .process-row, .inspection-row {
  margin-top: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.timeline-card {
  margin-bottom: 10px;
}
.link-section {
  margin-top: 10px;
}
.links {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.empty-data {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}
</style> 